package org.lilred.nzbberry.http.cookie;

import java.util.Enumeration;
import java.util.Hashtable;

import org.lilred.nzbberry.http.URL;

public class CookieClump {
	protected Hashtable _cookies = new Hashtable();

	public HttpCookie getCookie(String hash) {
		return (HttpCookie) _cookies.get(hash);
	}

	public void addCookie(HttpCookie cookie) {
		//The key is the actual HttpCookie, see the equals method in that class
		_cookies.put(cookie.getHashCode(), cookie);
	}

	public Enumeration getCookies() { return _cookies.keys(); }

	/**
	 * Get the cookies associated with this request
	 */
	public String getHeaderString(URL url) {
		StringBuffer s = new StringBuffer();
		Enumeration e = _cookies.keys();
		while (e.hasMoreElements()) {
			String key = (String) e.nextElement();
			HttpCookie cookie = getCookie(key);
			if (cookie.hasExpired()) _cookies.remove(key);
			if (cookie.domainMatches(url.getHost()) &&
				cookie.portMatches(url.getPort()) &&
				cookie.pathMatches(url.getPath())) {
				s.append(cookie.toString());
				if (e.hasMoreElements()) s.append(';');
			}
		}
		return s.toString();
	}

	public String toString() {
		StringBuffer s = new StringBuffer();
		Enumeration e = _cookies.keys();
		while (e.hasMoreElements()) {
			String key = (String) e.nextElement();
			HttpCookie cookie = getCookie(key);
			if (cookie.hasExpired()) _cookies.remove(key);
		}
		return s.toString();
	}
	
	/**
	 * Shallow copies a DomainCookies object.
	 * @return A shallow copy of the DomainCookies object
	 */
	public CookieClump clone() {
		CookieClump copiedCookies = new CookieClump();
		Enumeration e = getCookies();
		while (e.hasMoreElements()) {
			Object key = e.nextElement();
			copiedCookies.addCookie((HttpCookie) _cookies.get(key));
		}
		return copiedCookies;
	}

	/**
	 * Merge two sets of cookies from two domains.  This is most commonly used when making 
	 * an http request and cookies could come from either .domain.tld or sub.domain.tld
	 */
	public void addRequest(CookieClump cookies) {
		if (cookies == null) return;
		else {
			Enumeration e = cookies.getCookies();
			//Copy the second domain to a new object, then merge the cookies from the first domain
			//keeping the most recent ones and discarding the older ones.
			while (e.hasMoreElements()) {
				String key = (String) e.nextElement();
				addCookie(cookies.getCookie(key));
			}
		}
	}
}